//
//  SAShopAllocateVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2022/4/19.
//

#import "SAShopAllocateVC.h"
#import "SAShopAllocateCell.h"
#import "SAShopAllocateHeaderView.h"
#import "SAShopAllocateFooterView.h"
#import "SAAllocateDocumentsVC.h"
#import "SASearchShopNameView.h"
#import "SASearchStoreUserView.h"
#import "SAStoreUserModel.h"
#import "HDDatePickerView.h"
#import "SASystemStoreStoreListAPI.h"
#import "SAStoreModel.h"
#import "SAAllocateSelectShopVC.h"
#import "ScanHelper.h"
#import "SASalesOrderViewListModel.h"
#import "YBImageBrowser.h"
#import "SAStockDispatchSaveAPI.h"
#import "SACommodityAddShopSizeView.h"
#import "SAWarehousePurchaseFindProductPageAPI.h"
#import "SASalesOrderStatementErrorModel.h"
#import "SASalesOrderStatementErrorView.h"

@interface SAShopAllocateVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate, YBImageBrowserDataSource>

@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAStoreUserModel *userModel;
@property (nonatomic, strong) UIButton *shopNameBtn;
@property (nonatomic, strong) UIButton *empBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) SASystemStoreStoreListAPI *systemStoreStoreListAPI;
@property (nonatomic, strong) SAStoreModel *storeModel;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, strong) UILabel *shopCountLab;
@property (nonatomic, strong) SAStockDispatchSaveAPI *stockDispatchSaveAPI;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) NSString *timeFormatStr;
@property (nonatomic, strong) SAWarehousePurchaseFindProductPageAPI *warehousePurchaseFindProductPageAPI;

@end

@implementation SAShopAllocateVC

-(instancetype)initWithType:(NSString *)type {
    if (self = [super init]) {
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemStoreStoreListAPI == api) {
        NSMutableArray<SAStoreModel *> *storeList = [SAStoreModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        self.storeModel = nil;
        for (SAStoreModel *model in storeList) {
            if (model.merchantId > 0) {
                if (model.merchantId != [SAValueManger shareInStance].userInfo.merchantId) {
                    self.storeModel = model;
                    break;
                }
             }
        }
        if (self.storeModel != nil) {
            [self.shopNameBtn setTitle:self.storeModel.storeName forState:UIControlStateNormal];
            CGFloat imageWidth = self.shopNameBtn.imageView.bounds.size.width;
            CGFloat labelWidth = self.shopNameBtn.titleLabel.bounds.size.width;
            self.shopNameBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
            self.shopNameBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        }
        self.warehousePurchaseFindProductPageAPI.merchantId = @(self.storeModel.merchantId).stringValue;
    }else if (self.stockDispatchSaveAPI == api) {
        [self clearData];
        [Prompt popPromptViewWithMsg:@"新增成功" duration:2];
    }else if (self.warehousePurchaseFindProductPageAPI == api) {
        WeakSelf
        NSMutableArray *marr = [SASalesOrderViewListModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        if (marr.count == 1) {
            SASalesOrderViewListModel *model = marr[0];
            //判断model是否已经存在
            __block SASalesOrderViewListModel *dataModel = nil;
            for (SASalesOrderViewListModel *oldModel in weakSelf.dataMarr) {
                if ([oldModel.productId isEqualToString:model.productId]) {
                    dataModel = oldModel;
                }
            }
            
            if (dataModel != nil) {
                dataModel.targetSkuList = model.targetSkuList;
                model = dataModel;
            }
            
            SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
            addShopSizeView.isNegative = YES;
            addShopSizeView.isAll = YES;
            [addShopSizeView showView:self];
            addShopSizeView.showImageBlock = ^{
                [weakSelf showImage:model.imgList];
            };
            addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
                BOOL isZero = YES; //判断数据是否全是0，是就不添加
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock integerValue] != 0) {
                        isZero = NO;
                    }
                }
                if (isZero == NO) {
                    if (dataModel != nil) {
                        [weakSelf.dataMarr removeObject:dataModel];
                    }
                    [weakSelf.dataMarr insertObject:model atIndex:0];
                }else {
                    [weakSelf.dataMarr removeObject:dataModel];
                }
                [weakSelf refreshData];
            };
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.stockDispatchSaveAPI == api) {
        NSDictionary *dict = error.userInfo;
        if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"20007"]) {
            NSDictionary *errorDic = [self dictionaryWithJsonString:dict[@"msg"]];
            NSMutableArray *errorArray = [NSMutableArray array];
            for (NSArray *errorLsit in errorDic) {
                SASalesOrderStatementErrorModel *model = [SASalesOrderStatementErrorModel mj_objectWithKeyValues:errorLsit];
                NSLog(@"%@",model);
                [errorArray addObject:model];
            }

            SASalesOrderStatementErrorView *screenView = [SASalesOrderStatementErrorView shareCornView];
            screenView.removeBlock = ^(NSArray * _Nonnull array) {
                for (SASalesOrderViewListModel *model in self.dataMarr) {
                    for (SASalesOrderToPendSkuList *skuList in [model.toPendSkuAttrs reverseObjectEnumerator]) {
                        for (SASalesOrderStatementErrorSkuList *errorList in array) {
                            if ([errorList.skuId isEqualToString:skuList.skuId]) {
                                [model.toPendSkuAttrs removeObject:skuList];
                                break;
                            }
                        }
                    }
                }
                
                NSMutableArray *newDataArray = [NSMutableArray array];
                for (SASalesOrderViewListModel *listModel in self.dataMarr) {
                    if (listModel.toPendSkuAttrs.count > 0) {
                        [newDataArray addObject:listModel];
                    }
                }
                self.dataMarr = newDataArray;
                if (self.dataMarr.count > 0) {
                    [self refreshData];
                }else {
                    [self clearData];
                }
            };
            [screenView loadData:errorArray];
            [screenView showView:nil];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50001"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self clearData];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50002"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self clearData];
        }else {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
        }
    }else {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        [Prompt popPromptViewWithMsg:msg duration:2];
    }
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].skuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SAShopAllocateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAShopAllocateCell" forIndexPath:indexPath];
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].skuList[indexPath.row];
    cell.model = model;
    cell.countBlock = ^{
        [weakSelf countNum];
    };
    cell.selectBlock = ^{
        [weakSelf countNum];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SAShopAllocateHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAShopAllocateHeaderView"];
    SASalesOrderViewListModel *model = self.dataMarr[section];
    header.model = model;
    WeakSelf
    header.imageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    header.deleteBlock = ^{
        [weakSelf.dataMarr removeObject:model];
        [weakSelf refreshData];
    };
    header.addBlock = ^{
        [weakSelf addProduct:model];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SASalesOrderViewListModel *model = self.dataMarr[indexPath.section];
    SASalesOrderToPendSkuList *sku = model.skuList[indexPath.row];
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        if (model.skuList.count == 1) {
            [weakSelf.dataMarr removeObject:model];
        }else {
            sku.stock = @"0";
            sku.isSelecd = NO;
        }
        [weakSelf refreshData];
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - event
-(void)clickedScanBtn {
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:notSquare qrResultCallBack:^(id result) {
        if ([self.type isEqualToString:@"2"]) {
            self.warehousePurchaseFindProductPageAPI.merchantId = @(self.storeModel.merchantId).stringValue;
        }else {
            self.warehousePurchaseFindProductPageAPI.merchantId = @([SAValueManger shareInStance].userInfo.merchantId).stringValue;
        }
        self.warehousePurchaseFindProductPageAPI.currentPage = 1;
        self.warehousePurchaseFindProductPageAPI.pageSize = 20;
        self.warehousePurchaseFindProductPageAPI.productCodeOrBar = result;
        [self.warehousePurchaseFindProductPageAPI sendRequestToServerWithActivityViewAndMask:GET];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

-(void)addProduct:(SASalesOrderViewListModel *)model {
    WeakSelf
    SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
    addShopSizeView.isAll = YES;
    [addShopSizeView showView:self];
    addShopSizeView.showImageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
        SASalesOrderViewListModel *oldModel = nil;
        for (SASalesOrderViewListModel *model2 in weakSelf.dataMarr) {
            if ([model.productId isEqualToString:model2.productId]) {
                oldModel = model2;
                break;
            }
        }
        if (oldModel != nil) {
            [weakSelf.dataMarr removeObject:oldModel];
        }
        [weakSelf.dataMarr insertObject:model atIndex:0];
        [weakSelf refreshData];
    };
}

-(void)clickedAddBtn {
    SAAllocateSelectShopVC *shopVC = [[SAAllocateSelectShopVC alloc] initWithSelectMarr:self.dataMarr];
    if ([self.type isEqualToString:@"2"]) {
        shopVC.merchantId = @(self.storeModel.merchantId).stringValue;
    }else {
        shopVC.merchantId = @([SAValueManger shareInStance].userInfo.merchantId).stringValue;
    }
    [self.navigationController pushViewController:shopVC animated:YES];
    WeakSelf
    shopVC.selectBlock = ^(NSMutableArray<SASalesOrderViewListModel *> * _Nonnull selectMarr) {
        for (SASalesOrderViewListModel *model in self.dataMarr) {
            for (SASalesOrderToPendSkuList *sku in model.toPendSkuAttrs) {
                sku.isSelecd = NO;
            }
        }
        weakSelf.dataMarr = selectMarr;
        [weakSelf refreshData];
    };
}

-(void)clickedListBtn {
    if ([self.type isEqualToString:@"2"]) {
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *transferOrder = [NSString stringWithFormat:@"%@",menuList[10][@"perms"][@"transferOrder"]];
        if ([transferOrder isEqualToString:@"1"]) {
            [Prompt popPromptViewWithMsg:@"您没有查看调货单据权限,请联系店长添加" duration:2];
            return;
        }
        SAAllocateDocumentsVC *pushVC = [[SAAllocateDocumentsVC alloc] initWithType:@"2"];
        [self.navigationController pushViewController:pushVC animated:YES];
    }else {
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *distributionOrder = [NSString stringWithFormat:@"%@",menuList[10][@"perms"][@"distributionOrder"]];
        if ([distributionOrder isEqualToString:@"1"]) {
            [Prompt popPromptViewWithMsg:@"您没有查看配货单据权限,请联系店长添加" duration:2];
            return;
        }
        SAAllocateDocumentsVC *pushVC = [[SAAllocateDocumentsVC alloc] initWithType:@"1"];
        [self.navigationController pushViewController:pushVC animated:YES];
    }
}

-(void)clickedSearchShopBtn {
    if (self.dataMarr.count > 0) {
        [Prompt popPromptViewWithMsg:@"请先删除商品" duration:2];
        return;
    }
    WeakSelf
    SASearchShopNameView *view = [SASearchShopNameView shareCornView];
    view.selectBlock = ^(SAStoreModel * _Nonnull storeModel) {
        weakSelf.storeModel = storeModel;
        weakSelf.warehousePurchaseFindProductPageAPI.merchantId = @(self.storeModel.merchantId).stringValue;
        [weakSelf.shopNameBtn setTitle:[NSString stringWithFormat:@"%@",storeModel.storeName] forState:UIControlStateNormal];
        CGFloat imageWidth = weakSelf.shopNameBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.shopNameBtn.titleLabel.bounds.size.width;
        weakSelf.shopNameBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.shopNameBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        [weakSelf.shopNameBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    };
    UIViewController *vc = nil;
    [view showView:vc];
}

-(void)clickedUserBtn {
    SASearchStoreUserView *searchStoreUserView = [SASearchStoreUserView shareCornView];
    UIViewController *vc = nil;
    [searchStoreUserView showView:vc];
    WeakSelf
    searchStoreUserView.selectBlock = ^(SAStoreUserModel * _Nonnull userModel) {
        weakSelf.userModel = userModel;
        if (userModel.mobile.length > 0) {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@(%@)",userModel.empName,userModel.mobile] forState:UIControlStateNormal];
        }else {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@",userModel.empName] forState:UIControlStateNormal];
        }
        CGFloat imageWidth = weakSelf.empBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.empBtn.titleLabel.bounds.size.width;
        weakSelf.empBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.empBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        [weakSelf.empBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    };
}

-(void)clickedDateBtn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.dateBtn.titleLabel.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        [weakSelf.dateBtn setTitle:selectedDate forState:UIControlStateNormal];
        CGFloat imageWidth = weakSelf.dateBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.dateBtn.titleLabel.bounds.size.width;
        weakSelf.dateBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.dateBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
    };
}

//刷新数据处理
-(void)refreshData {
    double total = 0;
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        NSMutableArray<SASalesOrderToPendSkuList *> *skuList = [NSMutableArray array];
        for (SASalesOrderToPendSkuList *sku in model.toPendSkuAttrs) {
            if ([sku.stock doubleValue] > 0 || sku.isSelecd == YES) //大于0,或者选过了一次
            {
                sku.isSelecd = YES;//删除的时候注意 stock = 0  isSelecd = NO
                [skuList addObject:sku];
                total += [sku.stock doubleValue];
            }
        }
        model.skuList = skuList;
    }
    [self.tableView reloadData];
    if (self.dataMarr.count == 0) {
        self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(125), kScaleNum(260 + StatusHeight), kScaleNum(45), kScaleNum(65));
        self.scanBtn.frame = CGRectMake(kScaleNum(80), kScaleNum(260 + StatusHeight), kScaleNum(45), kScaleNum(65));
        self.shopCountLab.text = @"";
    }else {
        self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(125), kScreenHeight - kScaleNum(105) - SafeFooterHeight, kScaleNum(45), kScaleNum(65));
        self.scanBtn.frame = CGRectMake(kScaleNum(80), kScreenHeight - kScaleNum(105) - SafeFooterHeight, kScaleNum(45), kScaleNum(65));
        self.shopCountLab.text = [NSString stringWithFormat:@"总计:%0.lf件",total];
    }
}

-(void)countNum {
    double total = 0;
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        for (SASalesOrderToPendSkuList *sku in model.toPendSkuAttrs) {
            if ([sku.stock doubleValue] > 0) {
                total += [sku.stock doubleValue];
            }
        }
    }
    self.shopCountLab.text = [NSString stringWithFormat:@"总计:%0.lf件",total];
}

-(void)clearData {
    [self.dataMarr removeAllObjects];
    self.shopCountLab.text = @"";
    [self.tableView reloadData];
    self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(125), kScaleNum(260 + StatusHeight), kScaleNum(45), kScaleNum(65));
    self.scanBtn.frame = CGRectMake(kScaleNum(80), kScaleNum(260 + StatusHeight), kScaleNum(45), kScaleNum(65));
    [self.dateBtn setTitle: self.timeFormatStr forState:UIControlStateNormal];
    CGFloat imageWidth = self.dateBtn.imageView.bounds.size.width;
    CGFloat labelWidth = self.dateBtn.titleLabel.bounds.size.width;
    self.dateBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.dateBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
}

//防止多次结单
- (void)unisversalButtonAcrion:(UIButton *)sender {
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(clickedSettlementBtn) object:sender];
    [self performSelector:@selector(clickedSettlementBtn) withObject:sender afterDelay:0.3f];
}

-(void)clickedSettlementBtn {
    if (self.userModel == nil) {
        [Prompt popPromptViewWithMsg:@"请先选择店员" duration:2];
        return;
    }
    if (self.storeModel == nil) {
        [Prompt popPromptViewWithMsg:@"请先选择调出店" duration:2];
        return;
    }
    
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    NSMutableArray *detailFormArray = [[NSMutableArray alloc] init];
    mdic[@"dispatchType"] = self.type;
    mdic[@"empId"] = self.userModel.empId;
    mdic[@"empName"] = self.userModel.empName;
    mdic[@"remark"] = @"";
    mdic[@"targetMerchantId"] = @(self.storeModel.merchantId).stringValue;
    mdic[@"targetMerchantName"] = self.storeModel.merchantName;
    mdic[@"targetStoreName"] = self.storeModel.storeName;
    mdic[@"dispatchTime"] = self.dateBtn.titleLabel.text;
    
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        for (SASalesOrderToPendSkuList *skuList in model.skuList) {
            if ([skuList.stock integerValue] <= 0) {
                [Prompt popPromptViewWithMsg:@"调货数量不能为0" duration:2];
                return;
            }
            NSMutableDictionary *detailFormDic = [[NSMutableDictionary alloc] init];
            detailFormDic[@"count"] = skuList.stock;
            detailFormDic[@"entryPrice"] = model.entryPrice;
            detailFormDic[@"productCode"] = model.productCode;
            detailFormDic[@"productId"] = model.productId;
            detailFormDic[@"productName"] = model.productName;
            detailFormDic[@"remark"] = @"";
            detailFormDic[@"skuId"] = skuList.skuId;
            [detailFormArray addObject:detailFormDic];
        }
    }
    mdic[@"detailForms"] = detailFormArray;

    self.stockDispatchSaveAPI.coverParameters = mdic;
    [self.stockDispatchSaveAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    if ([self.type isEqualToString:@"2"]) {
        [self setNavigationItemBackBBIAndTitle:@"商品调货"];
    }else {
        [self setNavigationItemBackBBIAndTitle:@"商品配货"];
    }
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    
    self.userModel = [SAStoreUserModel new];
    self.userModel.empName = [SAValueManger shareInStance].userInfo.empName;
    self.userModel.empId = [SAValueManger shareInStance].userInfo.empId;
    self.userModel.mobile = [SAValueManger shareInStance].userInfo.mobile;
    
    UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    listBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [listBtn setImage:[UIImage imageNamed:@"shopSale_list"] forState:UIControlStateNormal];
    [listBtn addTarget:self action:@selector(clickedListBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[listBtn]];
    
    [self.view addSubview:self.tableView];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(252))];
    headerView.backgroundColor = kBgColor;
    self.tableView.tableHeaderView = headerView;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(203))];
    whiteView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:whiteView];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    self.timeFormatStr = timeFormatStr;
    
    NSArray *nameArr = @[@"申请店", @"调出店", @"店员", @"日期"];
    if ([self.type isEqualToString:@"1"]) {
        nameArr = @[@"配出店", @"接收店", @"店员", @"日期"];
    }
    for (int i = 0; i < nameArr.count; i++) {
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(20, i * 51, 70, 50)];
        titleLab.text = nameArr[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kBlackColor;
        [whiteView addSubview:titleLab];
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
        rightBtn.frame = SARectMake(0, i * 51, kBaseScreenWidth - 20, 50);
        rightBtn.titleLabel.font = kFont(15);
        [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [rightBtn setTitle:@"" forState:UIControlStateNormal];
        [whiteView addSubview:rightBtn];
        
        if (i == 1) {
            [rightBtn addTarget:self action:@selector(clickedSearchShopBtn) forControlEvents:UIControlEventTouchUpInside];
            self.shopNameBtn = rightBtn;
        }else if (i == 2) {
            [rightBtn addTarget:self action:@selector(clickedUserBtn) forControlEvents:UIControlEventTouchUpInside];
            self.empBtn = rightBtn;
            [rightBtn setTitle:[NSString stringWithFormat:@"%@(%@)",self.userModel.empName,self.userModel.mobile] forState:UIControlStateNormal];
        }else if (i == 3) {
            [rightBtn setTitle:timeFormatStr forState:UIControlStateNormal];
            [rightBtn addTarget:self action:@selector(clickedDateBtn) forControlEvents:UIControlEventTouchUpInside];
            self.dateBtn = rightBtn;
        }else {
            [rightBtn setTitle:[SAValueManger shareInStance].userInfo.storeName forState:UIControlStateNormal];
        }
        
        CGFloat imageWidth = rightBtn.imageView.bounds.size.width;
        CGFloat labelWidth = rightBtn.titleLabel.bounds.size.width;
        rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        
        if (i < 3) {
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(20, i * 50 + 50, kBaseScreenWidth - 40, 1)];
            line.backgroundColor = kLineColor;
            [whiteView addSubview:line];
        }
    }
    
    UIView *whiteView2 = [[UIView alloc] initWithFrame:SARectMake(kBaseScreenWidth - 30, 0, 30, 49)];
    whiteView2.backgroundColor = [UIColor whiteColor];
    [whiteView addSubview:whiteView2];
    
    UIView *whiteView3 = [[UIView alloc] initWithFrame:SARectMake(0, 211, kBaseScreenWidth, 40)];
    whiteView3.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:whiteView3];
    
    UILabel *shopLab = [[UILabel alloc] initWithFrame:SARectMake(20, 0, 150, 40)];
    shopLab.text = @"选择商品";
    shopLab.textColor = kBlackColor;
    shopLab.font = kFont(15);
    [whiteView3 addSubview:shopLab];

    UILabel *shopCountLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 190, 0, 170, 40)];
    shopCountLab.textColor = kBlackColor;
    shopCountLab.text = @"";
    shopCountLab.font = kFont(15);
    shopCountLab.textAlignment = NSTextAlignmentRight;
    [whiteView3 addSubview:shopCountLab];
    self.shopCountLab = shopCountLab;
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"Sale_Add2"] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(125), kScaleNum(260 + StatusHeight), kScaleNum(45), kScaleNum(65));
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    self.addBtn = addBtn;
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setImage:[UIImage imageNamed:@"Sale_scan2"] forState:UIControlStateNormal];
    scanBtn.frame = CGRectMake(kScaleNum(80), kScaleNum(260 + StatusHeight), kScaleNum(45), kScaleNum(65));
    [scanBtn addTarget:self action:@selector(clickedScanBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    self.scanBtn = scanBtn;
    
    UIButton *settlementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settlementBtn.frame = CGRectMake(0, kScreenHeight - (kScaleNum(40) + SafeFooterHeight), kScreenWidth, kScaleNum(40) + SafeFooterHeight);
    [settlementBtn setBackgroundImage:[UIImage imageNamed:@"top_image"] forState:UIControlStateNormal];
    [settlementBtn setTitle:@"调货" forState:UIControlStateNormal];
    settlementBtn.titleLabel.font = kBFont(18);
    [settlementBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [settlementBtn addTarget:self action:@selector(unisversalButtonAcrion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settlementBtn];
    
    if ([self.type isEqualToString:@"1"]) {
        [settlementBtn setTitle:@"配货" forState:UIControlStateNormal];
    }
    
    self.systemStoreStoreListAPI.returnAll = @"true";
    [self.systemStoreStoreListAPI sendRequestToServerWithType:GET];
}

#pragma mark - lazy
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 105) - SafeFooterHeight) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.bounces = NO;
        [_tableView registerClass:[SAShopAllocateCell class] forCellReuseIdentifier:@"SAShopAllocateCell"];
        [_tableView registerClass:[SAShopAllocateHeaderView class] forHeaderFooterViewReuseIdentifier:@"SAShopAllocateHeaderView"];
        [_tableView registerClass:[SAShopAllocateFooterView class] forHeaderFooterViewReuseIdentifier:@"SAShopAllocateFooterView"];
    }
    return _tableView;
}

-(SASystemStoreStoreListAPI *)systemStoreStoreListAPI {
    if (!_systemStoreStoreListAPI) {
        _systemStoreStoreListAPI = [SASystemStoreStoreListAPI apiWithDelegate:self];
    }
    return _systemStoreStoreListAPI;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SAStockDispatchSaveAPI *)stockDispatchSaveAPI {
    if (!_stockDispatchSaveAPI) {
        _stockDispatchSaveAPI = [SAStockDispatchSaveAPI apiWithDelegate:self];
    }
    return _stockDispatchSaveAPI;
}

-(SAWarehousePurchaseFindProductPageAPI *)warehousePurchaseFindProductPageAPI {
    if (!_warehousePurchaseFindProductPageAPI) {
        _warehousePurchaseFindProductPageAPI = [SAWarehousePurchaseFindProductPageAPI apiWithDelegate:self];
    }
    return _warehousePurchaseFindProductPageAPI;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
